﻿CREATE PROCEDURE [megasys].[ExportAccounts]
AS
BEGIN
SET NOCOUNT ON;

SELECT TrackerID,TMsAcM.XFA_CLASSACCOUNT, Status, XFA_DLRNO, XFA_OPENDT, XFA_VIN, XFA_ASTATUS, XFA_NAME, DealerID
INTO #Trackers
FROM megasys.TrackerBy_Ms_Ac_Martha AS TMsAcM
INNER JOIN t_Dealer_MsID AS DMsID ON TMsAcM.XFA_DLRNO = DMsID.MsID
INNER JOIN (
	SELECT MAX(XFA_CLASSACCOUNT) AS XFA_CLASSACCOUNT
	FROM         megasys.TrackerBy_Ms_Ac_Martha AS TMsAcM
	GROUP BY XFA_VIN
	HAVING      (XFA_VIN > '')
)V_A ON TMsAcM.XFA_CLASSACCOUNT = V_A.XFA_CLASSACCOUNT

DECLARE @MsID varchar(9),@LN sysname,@FN sysname,@LoanID varchar(50),@TrackerID varchar(11),@VIN varchar(18),@DealerID int
DECLARE @Count int SET @Count = 1
DECLARE cur CURSOR LOCAL READ_ONLY FOR SELECT XFA_CLASSACCOUNT,TrackerID,XFA_VIN,DealerID FROM #Trackers

OPEN cur

FETCH NEXT FROM cur INTO @MsID,@TrackerID,@VIN,@DealerID

--SET CONTEXT_INFO 0x2
WHILE @@FETCH_STATUS = 0-- AND @Count < 300
BEGIN
	IF NOT EXISTS(SELECT * FROM t_Loan WHERE MsID=@MsID ) BEGIN
		PRINT @Count SET @Count = @Count + 1
		/**/DECLARE @CI int EXEC @CI = sp__Context_ArchiveOff 1
		INSERT INTO t_Loan(MsID,MenuID,DealerSalesPersonID)
		SELECT @MsID,84,ID FROM t_Dealer_SalesPersons WHERE DealerID = @DealerID
		SET @LoanID = IDENT_CURRENT('t_Loan')
		IF @LoanID IS NULL BEGIN
			PRINT 'LoanID is NULL'
			RETURN
		END
		UPDATE t_CarInfo SET VIN = @VIN WHERE LoanID = @LoanID

		SELECT @LN = dbo.GetTokenLeft(XFA_NAME, N','), @FN = RTRIM(LTRIM(dbo.GetTokenRight(XFA_NAME, N',')))
		FROM #Trackers WHERE XFA_CLASSACCOUNT = @MsID

		EXEC s_Borrower_Add @LoanID
		IF @@ERROR <> 0 RETURN
		UPDATE v_Borrower_0 SET FirstName = @FN, LastName = @LN WHERE LoanID = @LoanID
		IF @@ERROR <> 0 RETURN
		EXEC sp__Context @CI
	END ELSE SELECT @LoanID = ID FROM t_Loan WHERE MsID = @MsID
	IF NOT EXISTS(SELECT * FROM t_Tracker_Car WHERE TrackerID = @TrackerID AND VIN = @VIN) BEGIN
		BEGIN TRAN TRACKER
		IF EXISTS(SELECT * FROM t_TrackerRequest WHERE LoanID = @LoanID AND StatusID = 0)BEGIN
			UPDATE t_TrackerRequest SET StatusID = 55,TechnicianID = -1 WHERE LoanID = @LoanID
			IF @@ERROR <> 0 RETURN
		END
		IF NOT EXISTS(SELECT * FROM t_Technician_Tracker WHERE TrackerID = @TrackerID)BEGIN
			EXEC s_Technician_Tracker_InHands -1,@TrackerID				IF @@ERROR <> 0 RETURN
		END
		PRINT 'LoanID:'+@LoanID+',MsID:'+@MsID+',VIN:'+@VIN
		EXEC s_Tracker_Car_Install DEFAULT,@TrackerID,@VIN		IF @@ERROR <> 0 RETURN
		COMMIT TRAN TRACKER
	END
	IF dbo.Stop() = 1 RETURN
	FETCH NEXT FROM cur INTO @MsID,@TrackerID,@VIN,@DealerID
END
END

